const formidable = require('formidable')
let path = require('path')
exports.uploadFile = (req, res) => {
  //1.创建上传对象
  let form = new formidable.IncomingForm();
  //2.设置编码格式
  form.encoding = 'utf-8';
  //3.设置文件存储目录
  form.uploadDir = __dirname + '/../uploads'
  //4.设置保留文件扩展名
  form.keepExtensions = true;
  //返回图片路径
  form.parse(req, (err, fields, files) => {
    if (err) {
      console.log(err);
      res.json({
        code: 400,
        msg: '文件上传失败'
      })
    } else {
      //获取最后一个'/'后的内容
      let imgName = path.basename(files.img.path);
      res.json({
        code: 200,
        msg: '文件上传成功',
        img: imgName
      })
    }
  })
}